package com.android.task5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


import android.util.Log;

public class FlickrXMLRPCRequest {
	
	private final static String INFO_TAG = "Flickr XML-RPC Request Info";
	
	private final static String baseUrl = "http://api.flickr.com/services/xmlrpc/";
	private final static String getInfoTag = "flickr.photos.getInfo"; //not used, for getInfo we use XML-RPC
	private final static String requestMethod = "POST";
	
	//XML-RPC specification
	private final static String agent = "Frontier/5.1.2";
	private final static String contentType = "text/xml";
	private final static String host = "betty.userland.com";
	
	
	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private Document doc;
	

	
	public FlickrXMLRPCRequest(){
		
		try {

			factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();
		
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void sendInfoRequest(String apiKey, String photoId){
		URL infoUrl;
		HttpURLConnection urlc = null;
		String data = createXMLRPCMessage(apiKey, photoId);
		char[] buffer = data.toCharArray();
		Log.i(INFO_TAG, data);
		try {
			infoUrl = new URL(baseUrl);
			urlc = (HttpURLConnection)infoUrl.openConnection();
			urlc.setRequestMethod(requestMethod);
			urlc.setDoOutput(true);
//			urlc.setDoInput(true);
//			urlc.setUseCaches(false);
			urlc.setRequestProperty("Content-Type", contentType);
			urlc.setRequestProperty("User-Agent", agent);
//			String length = buffer.length;
			Log.i(INFO_TAG, ""+ buffer.length);
			urlc.setRequestProperty("Content-Length",""+buffer.length);
			Log.i(INFO_TAG, "!!"+ data.substring(0,data.length()));
		
			OutputStreamWriter osw = new OutputStreamWriter(urlc.getOutputStream());
			osw.write(buffer);
			
			
			osw.flush(); 
			// Get the response
			InputStream is = urlc.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			final StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null)
			{
			sb.append(line);
			}
			br.close();
			Log.i(INFO_TAG, sb.toString());
			
			String output = sb.toString();
			String[] searchUsernameTable = output.split("username");
			searchUsernameTable = searchUsernameTable[1].split(";");
			searchUsernameTable = searchUsernameTable[1].split("&");
			String username = searchUsernameTable[0];
			Log.i(INFO_TAG, "username:" +username);
			
			String[] searchRealNameTable = output.split("realname");
			searchRealNameTable = searchRealNameTable[1].split(";");
			searchRealNameTable = searchRealNameTable[1].split("&");
			String realname = searchRealNameTable[0];
			Log.i(INFO_TAG, "realname:" +realname);
			
			String[] searchTitle = output.split("title");
			searchTitle = searchTitle[1].split(";");
			searchTitle = searchTitle[1].split("&");
			String title = searchTitle[0];
			Log.i(INFO_TAG, "title:" +title);
//			doc = builder.parse(is);
//		NodeList nodeList = doc.getElementsByTagName("string");
//			Log.i(INFO_TAG, nodeList.getLength()+"");
//			for(int i=0; i<nodeList.getLength(); i++){
//				if(nodeList.item(i) != null){
//					Node newNode = nodeList.item(i);
//				
//					String valueOfNode = newNode.getNodeValue();
//					Log.i(INFO_TAG, valueOfNode);
//				}
//				else{
//					Log.i(INFO_TAG, "Empty node");
//				}
//				
//			}
			
//			Element el = doc.getElementById("string");
//			Log.i(INFO_TAG, el.getNodeValue());
//			newEl.get
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//			catch (SAXException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

//	api_key (Required)
//	    Your API application key. See here for more details.
//	photoset_id (Required)
//	    The ID of the photoset to fetch information for. 
	public String createXMLRPCMessage(String api_key, String photo_id){

		String xmlHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

		String methodNameTag = createTag("methodName", "flickr.photos.getInfo");
		
		String stringTagForApiKey = createTag("string", api_key);
		String valueStringTag = createTag("value", stringTagForApiKey);
		String nameTag = createTag("name", "api_key");
		
		String memberTagForApiKey = createTag("member", nameTag+valueStringTag);
		
		String stringTagForPhotoId = createTag("string", photo_id);
		valueStringTag = createTag("value", stringTagForPhotoId);
		nameTag = createTag("name", "photo_id");
		
		String memberTagForPhotoId = createTag("member", nameTag+valueStringTag);
		
		String structTag = createTag("struct", memberTagForApiKey+memberTagForPhotoId);
		
		String valueTag = createTag("value",structTag);
		String paramTag = createTag("param", valueTag);
		String paramsTag = createTag("params", paramTag);
		
		String rootTag = createTag("methodCall", methodNameTag+paramsTag);
		return xmlHeader+rootTag;
	}

	public String createTag (String name, String value){
		String tag = "<" +name +">";
		tag += value;
		tag += "</" +name +">";
		return tag;
	}
	

//		
//		stringNode.setNodeValue(value);
//		valueNode.appendChild(stringNode);
//		nameNode.setNodeValue(name);
//		memberNode.appendChild(nameNode);
//		memberNode.appendChild(valueNode);
//		
//		return memberNode;
//	}
	

            
    
	
}
